<template>
  <div class="static-wrap curr-main">
    <el-dialog v-model="centerDialogVisible" title="新增标签" width="500px" center :close-on-click-modal="false">
      <span>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="90px" class="demo-ruleForm">
          <el-form-item label="标签名称:" prop="tag_name">
            <el-input v-model="ruleForm.tag_name"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submitForm" type="primary">保 存</el-button>
          <el-button @click="centerDialogVisible = false">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { addTag } from '../../../api/tags'
interface form {
  tag_name: string
}
export default defineComponent({
  name: 'addTag',
  setup(props, { emit }) {
    const centerDialogVisible = ref(false)//弹窗初始值
    const ruleFormRef = ref('ruleForm')//表单实列
    //新增标签参数
    const ruleForm: form = reactive({
      tag_name: '',
    })
    //校验规则
    const rules = {
      tag_name: [
        {
          required: true,
          message: '请输入标签名称',
          trigger: 'blur',
        },
      ],
    }
    //清空表单
    const resetForm = () => {
      ruleForm.tag_name = ''
    }
    //父组件调取子组件的方法
    const open = () => {
      centerDialogVisible.value = true
      resetForm()
      nextTick(() => {
        const ruleFormRefValue: any = ruleFormRef.value
        ruleFormRefValue.clearValidate()
      })
    }
    //保存
    const submitForm = () => {
      const ruleFormRefValue: any = ruleFormRef.value
      console.log(ruleFormRefValue)
      ruleFormRefValue.validate(async (valid: boolean) => {
        if (!valid) return
        const res = await addTag(ruleForm)
        if (res.data.code !== 200) {
          ElMessage({
            type: 'error',
            message: '新增失败',
          })
          return
        }
        ElMessage({
          type: 'success',
          message: '新增成功',
        })
        centerDialogVisible.value = false
        emit('updateTagList')
      })
    }
    return {
      centerDialogVisible,
      open,
      ruleForm,
      rules,
      ruleFormRef,
      submitForm,
      resetForm,
    }
  },
})
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  background-color: skyblue;
}
</style>